<template>
  <el-form :inline="true" class="demo-form-inline ">
    <div style="display: flex; justify-content: center;align-items: center;">
      <el-form-item>
        <el-button type="success" @click="addDialogShow=true">添加</el-button>
      </el-form-item>
      <el-form-item label="名称" style="float: right;">
        <el-input v-model="condition.name" placeholder="请输入要搜索的商品名称" @input="selectByPage(1)"/>
      </el-form-item>
      <el-form-item label="是否上下架" style="float: right;">
        <el-select v-model="condition.status"
                   placeholder="请输入要上下架的商品"
                   clearable
                   :value-on-clear="null"
                   style="width: 200px"
                   @change="selectByPage(1)">
          <el-option label="上架商品" value="1"/>
          <el-option label="下架商品" value="0"/>
        </el-select>
      </el-form-item>
      <el-form-item label="分类" style="float: right;">
        <el-cascader
            v-model="condition.categoryId"
            :options="allParent"
            :props="props"
            placeholder="请选择分类"
            clearable
            :value-on-clear="null"
            style="width: 200px"
            @change="selectByPage(1)"
        />
      </el-form-item>
    </div>
  </el-form>
  <el-table :data="pageInfo.list" style="width: 100%">
    <el-table-column prop="id" label="ID"/>
    <el-table-column prop="name" label="名称"/>
    <el-table-column label="图片">
      <template #default="scope">
        <el-popover placement="right" :width="250"  trigger="hover" v-if="scope.row.picList.length > 0">
          <template #reference>
            <el-image style="width: 50px; height: 40px"
                      :src="SERVER_ADDR + '/goods/pic/' + scope.row.picList[0].url"/>
          </template>
          <el-image v-for="(pic, index) in scope.row.picList"
                    :key="index"
                    style="width: 100px; height: 80px; margin-right: 12px;"
                    :src="SERVER_ADDR + '/goods/pic/' + pic.url"/>
        </el-popover>
      </template>
    </el-table-column>
    <el-table-column prop="dscp" label="描述"/>
    <el-table-column prop="price" label="售价"/>
    <el-table-column prop="markPrice" label="标价"/>
    <el-table-column prop="purchasePrice" label="进价"/>
    <el-table-column prop="color" label="颜色"/>
    <el-table-column prop="version" label="版本"/>
    <el-table-column prop="count" label="数量"/>
    <!--<el-table-column prop="recom" label="是否推荐">-->
    <!--  <template #default="scope">-->
    <!--    <el-tag type="warning" v-if="scope.row.recom===0">不推荐</el-tag>-->
    <!--    <el-tag type="success" v-if="scope.row.recom===1">推荐</el-tag>-->
    <!--  </template>-->
    <!--</el-table-column>-->
    <el-table-column label="使用状态">
      <template #default="scope">
        <el-switch
            v-model="scope.row.recom"
            inline-prompt
            style="--el-switch-off-color: #13ce66; --el-switch-on-color: #ff4949"
            active-text="不推荐"
            inactive-text="推荐"
            :active-value="0"
            :inactive-value="1"
            @change="updateRecom(scope.row.id,scope.row.recom,scope.row.picList)"
        />
      </template>
    </el-table-column>
    <el-table-column prop="tpoint" label="分类">
      <template #default="scope">
        <el-tag type="success">{{ scope.row.category.name }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="score" label="评分"/>
    <!--<el-table-column prop="status" label="是否上架">-->
    <!--  <template #default="scope">-->
    <!--    <el-tag type="warning" v-if="scope.row.status===0">下架</el-tag>-->
    <!--    <el-tag type="success" v-if="scope.row.status===1">上架</el-tag>-->
    <!--  </template>-->
    <!--</el-table-column>-->
    <el-table-column label="使用状态">
      <template #default="scope">
        <el-switch
            v-model="scope.row.status"
            inline-prompt
            style="--el-switch-off-color: #13ce66; --el-switch-on-color: #ff4949"
            active-text="下架"
            inactive-text="上架"
            :active-value="0"
            :inactive-value="1"
            @change="updateStatus(scope.row.id,scope.row.status,scope.row.picList)"
        />
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button type="primary" :icon="Search" color="green" @click="selectByIddetail(scope.row.id)"/>
        <el-button type="primary" :icon="Edit" color="blue" @click="selectById(scope.row.id)"/>
        <el-popconfirm title="你确认要删除嘛" confirm-button-text="确认" cancel-button-text="取消" width="200px"
                       @confirm="deleteCategory(scope.row.id)">
          <template #reference>
            <!--<el-button type="primary" :icon="Delete" color="red" @click="console.log(scope.row.tid)"-->
            <!--           v-if="scope.row.estate == 2" disabled/>-->
            <el-button type="primary" :icon="Delete" color="red" @click="console.log(scope.row.id)"/>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <el-row class="row-bg" justify="center">
    <el-pagination background layout="prev, pager, next"
                   v-model:current-page="pageInfo.pageNum"
                   :page-count="pageInfo.pages"
                   @update:current-page="selectByPage"
                   style="margin-top: 50px;"/>
  </el-row>

  <!-- 添加商品的对话框开始 -->
  <el-dialog v-model="addDialogShow" title="新增商品" width="800">
    <el-form label-width="20%">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="名称">
            <el-input autocomplete="off" v-model="goodsAdd.name" style="width: 300px"/>
          </el-form-item>
          <el-form-item label="描述">
            <el-input autocomplete="off" v-model="goodsAdd.dscp" style="width: 300px"/>
          </el-form-item>
          <el-form-item label="售价">
            <el-input autocomplete="off" v-model="goodsAdd.price" style="width: 300px"/>
          </el-form-item>
          <el-form-item label="标价">
            <el-input autocomplete="off" v-model="goodsAdd.markPrice" style="width: 300px"/>
          </el-form-item>
          <el-form-item label="进价">
            <el-input autocomplete="off" v-model="goodsAdd.purchasePrice" style="width: 300px"/>
          </el-form-item>
          <el-form-item label="颜色">
            <el-input autocomplete="off" v-model="goodsAdd.color" style="width: 300px"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="版本">
            <el-input autocomplete="off" v-model="goodsAdd.version" style="width: 300px"/>
          </el-form-item>
          <el-form-item label="数量">
            <el-input autocomplete="off" v-model="goodsAdd.count" style="width: 300px"/>
          </el-form-item>
          <el-form-item label="分类ID">
            <el-cascader
                v-model="goodsAdd.categoryId"
                :options="allParent"
                :props="props"
                placeholder="请选择分类"
                clearable
                :value-on-clear="null"
                style="width: 300px"
            />
          </el-form-item>
          <el-form-item label="是否推荐">
            <el-radio-group v-model="goodsAdd.recom" style="width: 300px">
              <el-radio :value="1" size="large">推荐</el-radio>
              <el-radio :value="0" size="large">不推荐</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="评分">
            <el-input autocomplete="off" v-model="goodsAdd.score" style="width: 300px"/>
          </el-form-item>
          <el-form-item label="是否上架">
            <el-radio-group v-model="goodsAdd.status" style="width: 300px">
              <el-radio :value="1" size="large">上架</el-radio>
              <el-radio :value="0" size="large">不上架</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="图片">
        <el-upload
            v-model:file-list="goodsAdd.picList"
            :action="SERVER_ADDR + '/goods/upload'"
            name="pic"
            :headers="headers"
            list-type="picture-card"
            :on-success="handleAvatarSuccessAdd"
            :before-upload="beforeAvatarUpload"
        >
          <el-icon>
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDialogShow = false">取消</el-button>
        <el-button @click="insert()">确定</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 添加商品的对话框结束 -->
  <!-- 修改商品的对话框开始 -->
  <el-dialog v-model="updateDialogShow" title="新增商品" width="800">
    <el-form label-width="20%">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="名称">
            <el-input autocomplete="off" v-model="goodsUpdate.name" style="width: 300px"/>
          </el-form-item>
          <el-form-item label="描述">
            <el-input autocomplete="off" v-model="goodsUpdate.dscp" style="width: 300px"/>
          </el-form-item>
          <el-form-item label="售价">
            <el-input autocomplete="off" v-model="goodsUpdate.price" style="width: 300px"/>
          </el-form-item>
          <el-form-item label="标价">
            <el-input autocomplete="off" v-model="goodsUpdate.markPrice" style="width: 300px"/>
          </el-form-item>
          <el-form-item label="进价">
            <el-input autocomplete="off" v-model="goodsUpdate.purchasePrice" style="width: 300px"/>
          </el-form-item>
          <el-form-item label="颜色">
            <el-input autocomplete="off" v-model="goodsUpdate.color" style="width: 300px"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="版本">
            <el-input autocomplete="off" v-model="goodsUpdate.version" style="width: 300px"/>
          </el-form-item>
          <el-form-item label="数量">
            <el-input autocomplete="off" v-model="goodsUpdate.count" style="width: 300px"/>
          </el-form-item>
          <el-form-item label="分类ID">
            <el-cascader
                v-model="goodsUpdate.categoryId"
                :options="allParent"
                :props="props"
                placeholder="请选择分类"
                clearable
                :value-on-clear="null"
                style="width: 300px"
            />
          </el-form-item>
          <el-form-item label="是否推荐">
            <el-radio-group v-model="goodsUpdate.recom" style="width: 300px">
              <el-radio :value="1" size="large">推荐</el-radio>
              <el-radio :value="0" size="large">不推荐</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="评分">
            <el-input autocomplete="off" v-model="goodsUpdate.score" style="width: 300px"/>
          </el-form-item>
          <el-form-item label="是否上架">
            <el-radio-group v-model="goodsUpdate.status" style="width: 300px">
              <el-radio :value="1" size="large">上架</el-radio>
              <el-radio :value="0" size="large">不上架</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="图片">
        <el-upload
            v-model:file-list="goodsUpdate.picList"
            :action="SERVER_ADDR + '/goods/upload'"
            name="pic"
            :headers="headers"
            list-type="picture-card"
            :on-success="handleAvatarSuccessAdd"
            :before-upload="beforeAvatarUpload"
        >
          <el-icon>
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateDialogShow = false">取消</el-button>
        <el-button @click="update()">确定</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 修改商品的对话框结束 -->
  <!-- 商品详情的对话框开始 -->
  <el-dialog v-model="detailDialogShow" title="商品详情" width="800">
    <div v-if="detailDialogShow" style="border: 1px solid #ccc">
      <Toolbar
          style="border-bottom: 1px solid #ccc"
          :editor="editorRef"
          :defaultConfig="toolbarConfig"
          :mode="mode"
      />
      <Editor
          style="height: 550px; overflow-y: hidden;"
          v-model="goodsUpdate.detail"
          :defaultConfig="editorConfig"
          :mode="mode"
          @onCreated="handleCreated"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="detailDialogShow = false">取消</el-button>
        <el-button @click="detailUpdate()">确定</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 商品详情的对话框结束 -->
</template>

<script setup>
import {Delete, Edit, Search, Share, Upload} from '@element-plus/icons-vue'
import {ElMessage, ElLoading} from 'element-plus';
import categoryApi from "@/api/categoryApi.js";
import goodsApi from "@/api/goodsApi.js";
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { useTokenStore } from '@/stores/token.js';//使用store
const tokenStore = useTokenStore();
//解决加了拦截器添加修改时上传图片传不上去的问题
const headers=computed(()=>{
  const token= tokenStore.tokenStr;
  return{
    token:token
  }
})

import {onBeforeUnmount, ref, shallowRef, onMounted, computed} from 'vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const mode = ref("default")
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR)
const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: `${SERVER_ADDR.value}/goods/upload`,
      fieldName: 'pic',
      //解决父文本编辑器上传图片传不上去的问题
      headers:{
        token:tokenStore.tokenStr
      },
      customInsert(resp, insertFn) {
        // res 即服务端的返回结果
        let url=`${SERVER_ADDR.value}/goods/pic/${resp.data}`
        //url--图片通过后台访问的地址
        insertFn(url)
      },
    }
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

//服务器路径
//const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR)
//搜索条件
const condition = ref({
  name: null,
  categoryId: null,
  status: null,
});
//分页信息
const pageInfo = ref({
  pages: 0,
  pageSize: 0,
  pageNum: 0,
})
//级联选择器的配置选项
const props = {
  //给级联选择器绑定的数据与官方不一样时进行设置
  value: 'id',//值
  label: 'name',//显示的信息
  children: 'childList',//子级
  emitPath: false,
}
const addDialogShow = ref(false)//操作新增的弹框出现
const goodsAdd = ref({//被添加父类子类商品的信息
  name: null,
  pic: null,
  dscp: null,
  detail: null,
  price: null,
  markPrice: null,
  purchasePrice: null,
  color: null,
  version: null,
  count: null,
  recom: 1,
  categoryId: 0,
  score: 0,
  status: 1,
  picList: [],
});
const updateDialogShow = ref(false);//操作修改的弹框出现
const goodsUpdate = ref({//被添加父类子类商品的信息
  id: "",
  name: null,
  pic: null,
  dscp: null,
  detail: "",
  price: null,
  markPrice: null,
  purchasePrice: null,
  color: null,
  version: null,
  count: null,
  recom: 1,
  categoryId: 0,
  score: 0,
  status: 1,
  picList: [],//url--保存图片在服务器上的名字
});
const detailDialogShow = ref(false);//商品详情的弹框出现
const allParent = ref([])//所有的父分类
//上传图片之前的回调
function beforeAvatarUpload(rawFile) {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片仅支持JPG格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
}

//添加图片上传成功的回调
//resp-服务器响应  uploadFile-当前上传的图片-和picList中对应的元素是绑定的
function handleAvatarSuccessAdd(resp, uploadFile, uploadFiles) {
  console.log(resp);
  if (resp.code == 10000) {
    ElMessage.success(resp.msg)
    uploadFile.url = `${SERVER_ADDR.value}/goods/pic/${resp.data}`;//全路径
    uploadFile.realName = resp.data;//图片名字
  } else {
    ElMessage.error(resp.msg)
  }
}

//成功修改上传头像之后的回调
function handleAvatarSuccessUpdate(resp, uploadFile) {
  console.log(resp);
  if (resp.code == 10000) {
    ElMessage.success(resp.msg)
    uploadFile.realName = resp.data;
  } else {
    ElMessage.error(resp.msg)
  }
}

//确认添加数据
function insert() {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  //处理图片 realName-->url 目的:让url属性保存文件名
  for (let i = 0; i < goodsAdd.value.picList.length; i++) {
    goodsAdd.value.picList[i].url = goodsAdd.value.picList[i].realName;
  }
  goodsApi.insert(goodsAdd.value)
      .then(resp => {
        loading.close()
        //判断---弹出消息--刷新表格
        if (resp.code == 10000) {
          //弹出消息
          ElMessage.success(resp.msg)
          //隐藏
          addDialogShow.value = false
          //清空
          goodsAdd.value = {
            name: null,
            pic: null,
            dscp: null,
            detail: null,
            price: null,
            markPrice: null,
            purchasePrice: null,
            color: null,
            version: null,
            count: null,
            recom: 1,
            categoryId: 0,
            score: 0,
            status: 1,
            picList: [],
          }
        } else {
          //弹出消息
          ElMessage.error(resp.msg)
        }
        //刷新表格
        selectByPage(1)
      })
}

//确定删除数据
function deleteCategory(id) {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  goodsApi.delete(id)
      .then(resp => {
        loading.close()
        //判断---弹出消息--刷新表格
        if (resp.code === 10000) {
          //弹出消息
          ElMessage.success(resp.msg)
        } else {
          //弹出消息
          ElMessage.error(resp.msg)
        }
        //刷新表格
        selectByPage(1)
      })

}

//定义根据id查询方法查询分类信息，回显数据
function selectById(id) {
  goodsApi.selectById(id)
      .then(resp => {
        //console.log(resp);
        goodsUpdate.value = resp.data
        //处理图片
        for (let i = 0; i < goodsUpdate.value.picList.length; i++) {
          //保存图片真实的名字
          goodsUpdate.value.picList[i].realName = goodsUpdate.value.picList[i].url;
          //让url改成全路径显示
          goodsUpdate.value.picList[i].url = `${SERVER_ADDR.value}/goods/pic/${goodsUpdate.value.picList[i].url}`;
        }
        //展示修改模态框
        updateDialogShow.value = true;
      })
}
function selectByIddetail(id) {
  goodsApi.selectById(id)
      .then(resp => {
        //console.log(resp);
        goodsUpdate.value = resp.data
        //处理图片
        for (let i = 0; i < goodsUpdate.value.picList.length; i++) {
          //保存图片真实的名字
          goodsUpdate.value.picList[i].realName = goodsUpdate.value.picList[i].url;
          //让url改成全路径显示
          goodsUpdate.value.picList[i].url = `${SERVER_ADDR.value}/goods/pic/${goodsUpdate.value.picList[i].url}`;
        }
        //展示修改模态框
        detailDialogShow.value = true;
      })
}
//按钮修改recom
function updateRecom(id,recom,picList){
  goodsApi.update({id,recom,picList})
      .then(resp=>{
        if (resp.code === 10000) {
          ElMessage.success(resp.msg)
        } else {
          ElMessage.error(resp.msg)
        }
        selectByPage(pageInfo.value.pageNum)
      })
}
//按钮修改status
function updateStatus(id,status,picList){
  goodsApi.update({id,status,picList})
      .then(resp=>{
        if (resp.code === 10000) {
          ElMessage.success(resp.msg)
        } else {
          ElMessage.error(resp.msg)
        }
        selectByPage(pageInfo.value.pageNum)
      })
}
//确认修改数据
function update() {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  //处理图片 realName-->url 目的:让url属性保存文件名
  for (let i = 0; i < goodsUpdate.value.picList.length; i++) {
    goodsUpdate.value.picList[i].url = goodsUpdate.value.picList[i].realName;
  }
  goodsApi.update(goodsUpdate.value)
      .then(resp => {
        loading.close()
        //判断---弹出消息--刷新表格
        if (resp.code === 10000) {
          //弹出消息
          ElMessage.success(resp.msg)
          //隐藏
          updateDialogShow.value = false
          //重置
          goodsUpdate.value = {//被添加父类子类商品的信息
            id: "",
            name: null,
            pic: null,
            dscp: "",
            detail: null,
            price: null,
            markPrice: null,
            purchasePrice: null,
            color: null,
            version: null,
            count: null,
            recom: 1,
            categoryId: 0,
            score: 0,
            status: 1,
            picList: [],//url--保存图片在服务器上的名字
          }
        } else {
          //弹出消息
          ElMessage.error(resp.msg)
        }
        selectByPage(pageInfo.value.pageNum)
      })
}
//修改商品详情信息
function detailUpdate() {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  //处理图片 realName-->url 目的:让url属性保存文件名
  for (let i = 0; i < goodsUpdate.value.picList.length; i++) {
    goodsUpdate.value.picList[i].url = goodsUpdate.value.picList[i].realName;
  }
  goodsApi.update(goodsUpdate.value)
      .then(resp => {
        loading.close()
        //判断---弹出消息--刷新表格
        if (resp.code === 10000) {
          //弹出消息
          ElMessage.success(resp.msg)
          //隐藏
          detailDialogShow.value = false
          //重置
          goodsUpdate.value = {//被添加父类子类商品的信息
            id: "",
            name: null,
            pic: null,
            dscp: "",
            detail: null,
            price: null,
            markPrice: null,
            purchasePrice: null,
            color: null,
            version: null,
            count: null,
            recom: 1,
            categoryId: 0,
            score: 0,
            status: 1,
            picList: [],//url--保存图片在服务器上的名字
          }
        } else {
          //弹出消息
          ElMessage.error(resp.msg)
        }
        selectByPage(pageInfo.value.pageNum)
      })
}
function selectByPage(pageNum) {
  goodsApi.selectByPage(condition.value, pageNum, 9)
      .then(resp => {
        pageInfo.value = resp.data
        //console.log(resp.data)
      })
}

//获取所有的父分类
function selectAllParent() {
  categoryApi.selectAllParent()
      .then(resp => {
        //console.log(resp.data)
        allParent.value = resp.data
      })
}

selectAllParent()
selectByPage(1)
</script>

<style scoped>
.avatar-uploader,
.avatar {
  width: 200px;
  height: 160px;
  display: block;
  border: 2px dotted #dcdfe6;
  border-radius: 5px;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 160px;
  text-align: center;
}
</style>